import os

from mbsh import create_app
from mbsh.core.models import to_json, LabelResult
from mbsh.plugins.endoscopic.video_fold import VideoFold

__author__ = 'gpu'

import unittest


class VideoFoldTestCase(unittest.TestCase):
    def setUp(self):
        app = create_app(os.getenv('FLASK_CONFIG') or 'default')
        app.app_context().push()
        self.app = app

    def test_list_page(self):
        video_fold = VideoFold(r'E:\projects\znyx\znyx-model\tests\res\video\01.0000000052427.0090.1521592248',
                               use_cache=False)

        imgs = video_fold.img_data_list
        # self.assertEqual(55, len(imgs))
        print(imgs[0])
        for img in imgs:
            if img['胃部分类26'] == 1:
                self.assertEqual(1, img['胃部分类'])

        to_json(video_fold)

        video_fold = VideoFold(r'E:\projects\znyx\znyx-model\tests\res\video\01.0000000052427.0090.1521592248',
                               use_cache=True)
        to_json(video_fold)
        video_fold.link_predict()
        print(video_fold.img_data_list[0])
        video_fold.clear_cache()

    def test_list_folds(self):
        video_db_path = r'E:\projects\znyx\znyx-model\tests\res\video'
        folds = VideoFold.list_folds(video_db_path)
        self.assertEqual(r'01.0000000052427.0090.1521592248', folds[0]['name'])
        folds = VideoFold.list_folds(video_db_path)
        self.assertEqual(r'01.0000000052427.0090.1521592248', folds[0]['name'])
        self.assertEqual('video', folds[0]['video_type'])

    def test_export_finished(self):
        video_db_path = r'E:\projects\znyx\znyx-model\tests\res\video'
        path = VideoFold.export_finished(video_db_path,'finished')
        self.assertEqual('d:\\znyx\\temp\\manual.zip', path)

    def test_detect(self):
        video_fold = VideoFold(r'E:\projects\znyx\znyx-model\tests\res\video\01.0000000052427.0090.1521592248')

        imgs = video_fold.img_data_list
        model_name = '胃部分类27'
        detect_list = []
        parts = {}

        for item_data in imgs:
            item = item_data['胃部分类27']

            if item not in parts:
                label_result = LabelResult(model_name, class_index=item, img_path=item_data['img_path'])
                parts[item] = label_result
                detect_list.append(label_result)
        print(to_json(detect_list))

        self.assertEqual(({2, 3, 9, 16}, {2, 3, 9, 16}), video_fold.stats_cover(model_name, detect_list))
        self.assertEqual(({16, 9, 2}, {16, 9, 2, 3}), video_fold.stats_cover(model_name, detect_list[:-1]))
        self.assertEqual((set(), {16, 9, 2, 3}), video_fold.stats_cover(model_name, []))
        self.assertEqual((set(), {16, 9, 2, 3}), video_fold.stats_cover(model_name, detect_list[:1]))


if __name__ == '__main__':
    unittest.main()
